<template>
	<div class="group" ref="groupBody">
		<div class="group-menu">
			<div class="scroll-bar">
				<div class="menu-container">
					<g-menu-item 
						v-for="item in menu"
						:data="item"
						:selected="selected"
						:key="item.name"
						@on-select="switchGroup"></g-menu-item>

		            <div class="menu-button-wrap" v-if="orgRole === 'admin'">
		                <div class="button-word" @click="addGroup">
		                	新建群组
		                </div>
		            </div>
		        </div>
		    </div>
		</div>
		<div class="group-body">
			<transition name="fade">
                <div class="content-loading" v-if="isSwitching">
                    <div class="conent-loading-animate">
                        <div></div><div></div><div></div>
                    </div>
                </div>
            </transition>
			<div class="group-body-content" >
				 <keep-alive>
					<router-view 
						@on-view-load="onLoad" 
						:groups="currentGroup.members" 
						:groupName="currentGroup.name"
						:orgName="currentGroup.orgName"
						:uid="currentGroup.key"
						:total="total"
						:memberLimit="memberLimit"
						v-on:remove-group="remove"
						v-on:remove-member="removeMember"
						v-on:rename="rename"
						v-on:reset-member="resetMember"
						v-on:update-group-members="updateGroupMembers"></router-view>
				 </keep-alive>
			</div>

		</div>

	</div>
</template>

<script>

	import Bus from '@/utils/event_bus'
	import GMenuItem from '@/components/common/g-menu-item'
	import {organization as orgAPI, group as groupAPI} from '@/api'

	const limit = 100;

	const menu = [
		{
			name: '群组',
			type: 'data',
			submenu: []
		},
	];

	export default{

		name: 'group',

		components: {
			GMenuItem,
		},

		data (){
			return {
				menu,
				selected: '',
				loading: true,
				currentMenu: '',
				waiting: false,
				orgUid: this.$root.org.orgUid,
				orgRole: this.$root.org.role,
				organizations: {
					all: {
						key: 'all',
						page: 1,
						name: '所有成员',
						members: [],
					}
				},
				currentGroup: {},
				isMounted: false,
				isSwitching: false,
				total: 0,
				memberLimit: 0
			}
		},

		activated () {
			let selected = this.selected;
			if (selected) {
				if (selected === 'all') {
	            	this.$router.push( { path: selected } );
	            } else {
	            	this.$router.push( { name: 'GroupMemebers', params: {groupUid: selected} } );
	            }
			}

			if (this.isMounted) {
				this.$emit( 'on-view-load' );
			}
	        
	    },

	    async mounted () {

	    	await this.getGroups();
	    	await this.getOrgMembers();

	    	Bus.$on('reset-group', () => {
	    		this.$destroy();
	    	})

	    	let path = this.$router.currentRoute.path;
			let paths = path.split('/');

			await this.switchGroup(paths[2]);

	    	this.isMounted = true;
	    	this.$emit( 'on-view-load' );

			Bus.$emit('on-submenu-change', this.currentGroup.name);
			Bus.$emit('on-submenu-change', '所有成员');

	    },

	    watch: {
	        async '$route.params.groupUid' ( name ) {
	            if (name) {
	            	await this.initGroup(name);
	            }
	        }
	    },

		methods: {

			async getGroups () {

				if (!this.orgUid) {
					return;
				}
				
				let result = await orgAPI.summary(this.orgUid);

				if (!result || result.data.code != 0) {
					this.$message.error('获取群组失败');
					return;
				}

				let data = result.data.data;
				let groups = data.groups;
				let members = data.members; 
				this.memberLimit = data.memberLimit;

				let arr = [{
					name: '所有成员',
					key: 'all',
					icon:'all-members',
					count: members
				}]

				this.organizations.all.name = data.name;
				this.total = members;

				groups.forEach( n => {

					arr.push({
						name: n.name,
						key: n.uid,
						icon: 'group',
						count: n.members
					})

				});

				this.menu[0].submenu = arr;
			},

			async initGroup (key) {

				let group = this.organizations[key];

				if (!group || !group.members.length) {

					this.isSwitching = true;

					let name = this.menu[0].submenu.filter(n => n.key === key);
					name = name[0]['name'];

					this.organizations[key] = {
						key,
						name,
						page: 1,
						members: []
					};

					await this.getData(key);

					this.currentGroup = Object.assign( {}, this.organizations[key] );
					this.isSwitching = false;

					return;
				}

			},

			async getOrgMembers () {

				if (!this.orgUid) {
					return;
				}

				let group = this.organizations['all'];
				let page = group.page;

				let result = await orgAPI.memberList(this.orgUid, {page, limit});

				if (!result || result.data.code != 0) {
					this.$message.error('获取成员失败');
					return;
				}

				let members = result.data.data;

				group.members = group.members.concat(members) ;
			},

			async getData (key) {

				let group = this.organizations[key];
				let page = group.page;
				let result = await groupAPI.memberList(key, {page, limit});

				if (result.data.code != 0) {
					this.$message.error('获取成员失败');
					return;
				}

				let members = result.data.data;

				group.members = group.members.concat(members);
			},

			async switchGroup( key ){
				if ( key === this.selected ) return;
	            this.selected = key;

	            await this.initGroup(key);

	            this.currentGroup = Object.assign( {}, this.organizations[key] );

	            if (key === 'all') {
	            	this.$router.push( { path: key } );
	            } else {
					
	            	this.$router.push( { name: 'GroupMemebers', params: {groupUid: key} } );
	            }
			},

			addGroup () {

				if (this.waiting) return;

				let inputPattern = /^[\u4E00-\u9FA5_A-Za-z0-9-（）()]{2,20}$/;

				let promise = this.$prompt(' ', '新建群组', {
	                confirmButtonText: '确定',
	                cancelButtonText: '取消',
	                inputErrorMessage: '群组名称包含非法字符',
	                inputPlaceholder: '输入群组名称，2-20个汉字、字母、数字',

	                startWaiting: (instance) => {
                    	instance.editorErrorMessage = null;
                        instance.$refs.input.classList.remove('invalid');

                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '操作中...';
                        instance.cancelButtonDisabled = true;
                    },
                    stopWaiting: (instance) => {
                    	instance.confirmButtonLoading = false;
                        instance.confirmButtonText = '确定';
                        instance.cancelButtonDisabled = false;
                    },

	                beforeClose: async(action, instance, done) => {

	                    if (action === 'confirm') {

		                    let inputValue = instance.inputValue;

		                    if (inputValue.length > 20 || inputValue.length < 2) {
	                        	instance.editorErrorMessage = '群组名称应当为2-20个汉字、字母或数字';
                                instance.$refs.input.classList.add('invalid');
                                return;
	                        }

		                    let ok = inputPattern.test(inputValue);

		                    if (!ok) {
                                instance.editorErrorMessage = '群组名称包含非法字符';
                                instance.$refs.input.classList.add('invalid');
                                return;
                            }

                            instance.startWaiting(instance);

	                        this.waiting = true;
	                        let result = '';

		                    if (inputValue) {

		                    	let result = await groupAPI.create({ name: inputValue})

			                    if (!result) {
                                	this.$message.error('新建群组失败');
		                            this.waiting = false;
			                    	instance.stopWaiting(instance);
			                    	done();
									return;
								}

								if (result.data.code === 613) {
		                    		instance.editorErrorMessage = `群组 ${inputValue} 已存在, 请更换名称重试`;
                                	instance.$refs.input.classList.add('invalid');
		                            this.waiting = false;
			                    	instance.stopWaiting(instance);
									return;
								}

								if (result.data.code != 0) {
                                	this.$message.error('新建群组失败');
		                            this.waiting = false;
			                    	instance.stopWaiting(instance);
									return;
								}

			                    let menu = this.menu;
			                    let groups = menu[0].submenu;
			                    let data = result.data.data;

			                    groups.push({
			                    	name: inputValue,
									key: data.uid,
									icon:'group',
									count: 0
			                    })

			                    done();
			                    this.$message.success('创建成功');
			                    this.switchGroup(data.uid);

		                    }

	                        done();
	                        instance.confirmButtonLoading = false;
	                        this.waiting = false;

	                    } else {
	                        done();
	                        this.waiting = false;
	                    }
	                }
	            })

	            promise.then(async({value}) => { }).catch(() => { });
			},

			onLoad () {
	            this.loading = false;
	        },

	        async remove (uid) {

	        	let success = false;

	        	let promise = this.$confirm(
	                `群组删除后不可恢复，确认删除？`,
	                '删除',
	                {
	                    type: 'warning',
	                    confirmButtonType: 'danger',
	                    confirmButtonText: '删除',

	                    beforeClose: async (action, instance, done) => {

	                        if (action === 'confirm') {
	                            instance.confirmButtonLoading = true;
	                            instance.confirmButtonText = '删除中...';
	                            instance.cancelButtonDisabled = true;

	                            let result = await groupAPI.remove(uid);

					        	if (!result || result.data.code != 0) {
									this.$message.error('删除群组失败');
									done();
									return;
								}
								success = true;
								done();
								this.$message.success('删除群组成功');

	                            instance.confirmButtonLoading = false;

	                        } else {
	                            done();
	                        }

	                    }
	                }
	            );

	            promise.then(() => {

	            	if (!success) return;

	                this.switchGroup('all');

					let menu = this.menu[0].submenu;

					menu = menu.filter(n => n.key != uid);
 					this.menu[0].submenu = [].concat(menu);
					delete this.organizations[uid];

	            }).catch(() => { })

	        },

	        removeMember (key, memberUid) {

	        	if (key === 'all') {
	        		let keys = Object.keys(this.organizations);
	        		keys.forEach( (n) => {
	        			this.removeFromGroup(n, memberUid);
	        		})

	        		this.getGroups();

	        	} else {

	        		this.removeFromGroup(key, memberUid);

	        		let menu = this.menu[0].submenu;

	        		menu.forEach(n => {
	        			if (n.key === key) {
	        				n.count--;
	        			}
	        		})
	        	}

	        },

	        removeFromGroup (key, memberUid) {
	        	let group = this.organizations[key];
	        	let members = group.members;
	        	let index = members.findIndex(n => n.uid === memberUid);

	        	if (index >= 0) {
	        		members.splice(index, 1);
	        	}
	        },

	        rename (key, name) {

				this.organizations[key].name = name;

				let menu = this.menu[0].submenu;

				menu.forEach(n => {
					if (n.key === key) {
						n.name = name
					}
				})

			},

			resetMember() {
				for(let group in this.organizations){
					if(group !== 'all'){
						this.organizations[group].members = [];
					}
				}
			},
			
			updateGroupMembers (choosedMembers,key) {
				
				this.getGroups();

				let group = this.organizations[key];

				if (group) {
					group.members = group.members.concat(choosedMembers);
					this.currentGroup = Object.assign( {}, group );
				}
				
			}
		}
	}
</script>

<style lang="scss">

	@import 'common';

	@function delay($interval, $count, $index) {
    	@return ($index * $interval) - ($interval * $count);
	}

	@mixin ball-pulse-sync($n: 3, $start: 1) {
	    @for $i from $start through $n {
	        > div:nth-child(#{$i}) {
	            animation: ball-pulse-sync 0.6s delay(0.07s, $n, $i) infinite ease-in-out;
	        }
	    }
	}
	.group{
		height: 100%;
		overflow: hidden;

		.group-menu{
			float:left;
			height: 100%;
			width: 180px;
			overflow: hidden;

			.submenu-item-icon {
				> i {
					font-size: 12px !important;
				}
			}

            .menu-button-wrap{
                padding-top: 20px;

                .button-word {
                	user-select: none;
                	height: 30px;
                	line-height: 28px;
                	width: 120px;
                	border-radius: 3px;
                	border: 1px solid $primary;
                	color: $primary;
                	text-align: center;
                	margin: 0 auto;
                	cursor: pointer;

                	&:hover {
                		border: 1px solid $darkPrimary;
                		color: $darkPrimary;
                		font-weight: 500;
                	}
                }
            }       
		}

		.group-body{
			height: 100%;
			overflow: hidden;
			position: relative;
			
			.group-body-content{
				width: 100%;
				height: 100%;
			}
		}

		>.g-message-box-wrapper {

			background-color: rgba(0,0,0, 0.5);

			.g-message-box {

				box-shadow: 0 0 16px 1px rgba(0,0,0, 0.2);

				.g-message-box-header {
				    padding: 0 20px 0;
				    height: 49px;
				    line-height: 48px;
				    border-bottom: 1px solid $bdGray;

				    > i {
				    	top: 16px;
				    }
				}

				.g-message-box-content{
					// background-color: $bgMessage;
					padding: 30px 20px 0;
				}

				.g-message-box-footer {
					// background-color: $bgMessage;
				}

			}
		}
		
	}
</style>